const { createApp, ref, computed, onMounted, onUnmounted } = require('vue');
const { ipcRenderer } = require('electron');
const remote = require('@electron/remote');
const { dialog } = remote;
const ElementPlus = require('element-plus');
const { ElMessage, ElNotification } = ElementPlus;

// Store timeouts for each reminder
const reminderTimeouts = new Map();

// Create Vue app
const app = createApp({
    setup() {
        const reminders = ref(JSON.parse(localStorage.getItem('reminders') || '[]'));
        const currentTime = ref('');
        const newReminder = ref({
            title: '',
            description: '',
            dateTime: ''
        });

        // Computed property for sorted reminders
        const sortedReminders = computed(() => {
            return [...reminders.value].sort((a, b) => new Date(a.dateTime) - new Date(b.dateTime));
        });

        // Methods
        function updateCurrentTime() {
            const now = new Date();
            const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
            const weekday = weekdays[now.getDay()];
            
            // Skip display if it's Saturday
            if (now.getDay() === 6) {
                currentTime.value = '';
                return;
            }

            const year = now.getFullYear();
            const month = now.getMonth() + 1;
            const day = now.getDate();
            const hour = now.getHours().toString().padStart(2, '0');
            const minute = now.getMinutes().toString().padStart(2, '0');
            const second = now.getSeconds().toString().padStart(2, '0');

            currentTime.value = `${hour}:${minute}:${second}`;
        }

        // Start updating time immediately
        updateCurrentTime();
        const timeInterval = setInterval(updateCurrentTime, 1000);

        function saveReminders() {
            localStorage.setItem('reminders', JSON.stringify(reminders.value));
        }

        function createReminder() {
            if (!newReminder.value.title || !newReminder.value.dateTime) {
                ElMessage({
                    message: 'Please fill in at least the title and date/time',
                    type: 'warning'
                });
                return;
            }

            const reminder = {
                id: Date.now(),
                title: newReminder.value.title,
                description: newReminder.value.description,
                dateTime: newReminder.value.dateTime,
                isCompleted: false
            };

            reminders.value.push(reminder);
            saveReminders();
            scheduleReminder(reminder);
            clearForm();
            ElMessage({
                message: 'Reminder created successfully',
                type: 'success'
            });
        }

        function clearReminderTimeout(reminderId) {
            if (reminderTimeouts.has(reminderId)) {
                clearTimeout(reminderTimeouts.get(reminderId));
                reminderTimeouts.delete(reminderId);
            }
        }

        async function confirmDelete(reminder) {
            try {
                await ElMessageBox.confirm(
                    `Are you sure you want to delete the reminder "${reminder.title}"?`,
                    'Confirm Deletion',
                    {
                        confirmButtonText: 'Delete',
                        cancelButtonText: 'Cancel',
                        type: 'warning'
                    }
                );
                
                // Clear the timeout for this reminder
                clearReminderTimeout(reminder.id);
                
                // Remove from reminders list
                reminders.value = reminders.value.filter(r => r.id !== reminder.id);
                saveReminders();
                
                ElMessage({
                    type: 'success',
                    message: 'Reminder deleted successfully'
                });
            } catch {
                // User cancelled the deletion
            }
        }

        function scheduleReminder(reminder) {
            const reminderTime = new Date(reminder.dateTime).getTime();
            const currentTime = new Date().getTime();
            const timeUntilReminder = reminderTime - currentTime;

            if (timeUntilReminder > 0) {
                // Clear any existing timeout for this reminder
                clearReminderTimeout(reminder.id);
                
                // Set new timeout
                const timeoutId = setTimeout(() => {
                    showNotification(reminder);
                    reminderTimeouts.delete(reminder.id);
                }, timeUntilReminder);
                
                // Store the timeout ID
                reminderTimeouts.set(reminder.id, timeoutId);
            }
        }

        function showNotification(reminder) {
            new Notification(reminder.title, {
                body: reminder.description || 'Reminder!'
            });
            ElNotification({
                title: reminder.title,
                message: reminder.description || 'Reminder!',
                type: 'info',
                duration: 0
            });
        }

        function clearForm() {
            newReminder.value = {
                title: '',
                description: '',
                dateTime: ''
            };
        }

        function formatDateTime(dateTime) {
            return new Date(dateTime).toLocaleString();
        }

        function isPastReminder(reminder) {
            return new Date(reminder.dateTime) < new Date();
        }

        // Setup timers and initial state
        onMounted(() => {
            // Schedule all existing reminders
            reminders.value.forEach(reminder => {
                if (!isPastReminder(reminder)) {
                    scheduleReminder(reminder);
                }
            });
        });

        // Cleanup when component is unmounted
        onUnmounted(() => {
            // Clear the time update interval
            clearInterval(timeInterval);
            
            // Clear all reminder timeouts
            reminderTimeouts.forEach(timeoutId => clearTimeout(timeoutId));
            reminderTimeouts.clear();
        });

        return {
            reminders,
            currentTime,
            newReminder,
            sortedReminders,
            createReminder,
            confirmDelete,
            formatDateTime,
            isPastReminder
        };
    }
});

// Use Element Plus
app.use(ElementPlus);

// Mount Vue app
app.mount('#app');